package com.ruoyi.warning.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.ruoyi.common.core.base.Result;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.PageHik;
import com.ruoyi.common.hik.*;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.warning.domain.entity.Area;
import com.ruoyi.warning.domain.entity.Device;
import com.ruoyi.warning.domain.entity.Event;
import com.ruoyi.warning.service.HikApiService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 海康监控的服务实现类
 * </p>
 *
 * @author chenhc
 * @since 2025-02-06
 */
@Service
public class HikApiServiceImpl implements HikApiService {
    @Value("${hik.artemis.host}")
    private String host = "172.30.30.89:443";
    @Value("${hik.artemis.appKey}")
    private String appKey = "28868158";
    @Value("${hik.artemis.appSecret}")
    private String appSecret = "WEOkGBmfv1AdQXvSRJNI";
    @Value("${hik.artemis.pathKey}")
    private String pathKey = "https://";
    @Value("${hik.artemis.path}")
    private String path = "/artemis";
    @Resource
    private SysDictDataMapper sysDictDataMapper;
//    private String path = "/artemis";
//    private String host = "172.30.30.89:443";
//    private String pathKey = "https://";
//    private String appSecret = "WEOkGBmfv1AdQXvSRJNI";
//    private String appKey = "28868158";
    public static void main(String[] args_) throws Exception {
        /**
         * STEP1：设置平台参数，根据实际情况,设置host appkey appsecret 三个参数.
         */
        ArtemisConfig.host = "172.30.30.89:443"; // 平台的ip端口
        ArtemisConfig.appKey = "28868158";  // 密钥appkey
        ArtemisConfig.appSecret = "WEOkGBmfv1AdQXvSRJNI";// 密钥appSecret

        /**
         * STEP2：设置OpenAPI接口的上下文
         */
        final String ARTEMIS_PATH = "/artemis";

        /**
         * STEP3：设置接口的URI地址
         */
        final String previewURLsApi = ARTEMIS_PATH + "/api/els/v1/events/search";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", previewURLsApi);//根据现场环境部署确认是http还是https
            }
        };

        /**
         * STEP4：设置参数提交方式
         */
        String contentType = "application/json";

        /**
         * STEP5：组装请求参数
         */
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("startTime", "2025-02-15T12:11:38.154+08:00");
        jsonBody.put("endTime", "2025-02-17T12:11:38.154+08:00");
        jsonBody.put("pageSize", 10);
        jsonBody.put("pageNo", 1);
        String body = jsonBody.toJSONString();
        /**
         * STEP6：调用接口
         */
        String jsonString = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType , null);// post请求application/json类型参数

        Result result = JSON.parseObject(jsonString, Result.class);
        PageHik pageHik = JSON.parseObject(result.getData().toString(), PageHik.class);
        System.out.println(pageHik.getList());
        Events events = JSON.parseObject(pageHik.getList().get(0).toString(), Events.class);
        String data = events.getEventLogSrcList().get(0).getData().replace("\\","");
        EventLogData eventLogData = JSON.parseObject(data.substring(1, data.length() - 1), EventLogData.class);
        events.getEventLogSrcList().get(0).setEventLogData(eventLogData);
        events.getEventLogSrcList().get(0).setEventLogData(eventLogData);

        System.out.println("！！！！输出: " + events);
        //System.out.println(events.getEventLogSrcList().get(0).getData().replace("\\",""));

        System.out.println("！！！！输出: " + eventLogData);

        Event event=new Event();
        BeanUtils.copyProperties(events.getEventLogSrcList().get(0),event);
        BeanUtils.copyProperties(events,event);
        event.setWarningTime(events.getStartTime().toLocalDateTime());
        String url = eventLogData.getThermometry().get(0).getImageUrl();
        url = url.substring(url.indexOf("/pic"));
//        String imageUrl = this.picture(url,eventLogData.getThermometry().get(0).getTargetAttrs().getImageServerCode());
//        event.setImageUrl(imageUrl);
        System.out.println(event);


    }

    //查询编码设备列表
    @Override
    public Map<String, EncodeDevice> encodeDeviceSearch() {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 100);
        Result result = hikRequest("/api/resource/v2/encodeDevice/search",jsonBody);

        PageHik pageHik = JSON.parseObject(result.getData().toString(), PageHik.class);
        Map<String, EncodeDevice> map = new HashMap<>();
        if(ObjectUtils.isNotEmpty(pageHik.getList())){
            for(Object obj : pageHik.getList()){
                EncodeDevice encodeDevice = JSON.parseObject(obj.toString(), EncodeDevice.class);
                map.put(encodeDevice.getRegionIndexCode(),encodeDevice);
            }
        }
        return map;
    }
    //获取所有的监测点信息
    @Override
    public List<Device> cameraList() {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 100);

        Result result = hikRequest("/api/resource/v1/camera/advance/cameraList",jsonBody);

        PageHik pageHik = JSON.parseObject(result.getData().toString(), PageHik.class);
        System.out.println(pageHik.getList());
        List<Device> deviceList = new ArrayList<>();
        for(Object obj : pageHik.getList()){
            Camera camera = JSON.parseObject(obj.toString(), Camera.class);
            Device device = new Device();
            BeanUtils.copyProperties(camera,device);
            deviceList.add(device);
        }
        return deviceList;
    }
    //获取所有的摄像头信息
    @Override
    public List<Device> cameraSearch(JSONObject jsonBody) {
        Result result = hikRequest("/api/resource/v2/camera/search",jsonBody);

        if(ObjectUtils.isEmpty(result)){
            return null;
        }
        PageHik pageHik = JSON.parseObject(result.getData().toString(), PageHik.class);
        List<Device> deviceList = new ArrayList<>();
//        Map<String,EncodeDevice> map = this.encodeDeviceSearch();
        for(Object obj : pageHik.getList()){
            Camera camera = JSON.parseObject(obj.toString(), Camera.class);
            System.out.println("++++++++++");
            System.out.println(camera);
            Device device = new Device();
            BeanUtils.copyProperties(camera,device);
            deviceList.add(device);
        }
        return deviceList;
    }
    //获取所有的摄像头信息
    @Override
    public List<Device> cameraList(JSONObject jsonBody) {
        Result result = hikRequest("api/resource/v1/cameras",jsonBody);

        PageHik pageHik = JSON.parseObject(result.getData().toString(), PageHik.class);
        System.out.println(pageHik.getList());
        List<Device> deviceList = new ArrayList<>();
        for(Object obj : pageHik.getList()){
            Camera camera = JSON.parseObject(obj.toString(), Camera.class);
            Device device = new Device();
            BeanUtils.copyProperties(camera,device);
            deviceList.add(device);
        }
        return deviceList;
    }
    //获取根区域信息
    @Override
    public void getRoot() {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("treeCode", "0");

        Result result = hikRequest("/api/resource/v1/regions/root",jsonBody);
        System.out.println("result结果示例: " + result);
    }
    //获取关联事件
    @Override
    public List<Events> searchEvents(String startTime, String endTime, String pageSize, String pageNo) throws UnsupportedEncodingException {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("startTime", startTime);
        jsonBody.put("endTime", endTime);
        jsonBody.put("pageSize", pageSize);
        jsonBody.put("pageNo", pageNo);
        System.out.println("jsonBody: " + jsonBody);
        Result result = hikRequest("/api/els/v1/events/search",jsonBody);
        System.out.println("result结果示例: " + result);
        if(ObjectUtils.isEmpty(result)||ObjectUtils.isEmpty(result.getData())){
            return null;
        }
        PageHik pageHik = JSON.parseObject(result.getData().toString(), PageHik.class);
        System.out.println(pageHik.getList());
        List<Events> eventsList = new ArrayList<>();
        for(Object o : pageHik.getList()){
            Events events = JSON.parseObject(o.toString(), Events.class);
            String data = events.getEventLogSrcList().get(0).getData().replace("\\","");
//            System.out.println(data.replaceAll("[^\\x20-\\x7E]", "这里"));
//            data = data.replaceAll("[^\\x20-\\x7E]", "");
//            data = data.replaceAll("\\\\", "");
            EventLogData eventLogData;
            if(data.charAt(0)=='"'){
                eventLogData = JSON.parseObject(data.substring(1, data.length() - 1), EventLogData.class);
            }else {
                eventLogData = JSON.parseObject(data, EventLogData.class);
            }
//            EventLogData eventLogData = JSON.parseObject(data.substring(1, data.length() - 1), EventLogData.class);
            events.getEventLogSrcList().get(0).setEventLogData(eventLogData);
            eventsList.add(events);
        }
        java.util.Collections.reverse(eventsList);
        return eventsList;
    }
    //根据事件获取图片
    @Override
    public String picture(String svrIndexCode,String picUri) {
        JSONObject jsonBody = new JSONObject();
//        jsonBody.put("svrIndexCode", "bd2399ba-a347-4bce-9739-d2d9afc57398");
//        jsonBody.put("picUri", "/pic?ad00=a402l8e-do8e1a*64f6*5o9=0=2840*7l5414947177*3t1=0*5ps===118**8b0f677ed-9cb522a-190oe4-pi0c1d=00910");
        jsonBody.put("svrIndexCode", svrIndexCode);
        jsonBody.put("picUri", picUri);
        jsonBody.put("netProtocol", "http");

        Result result = hikRequest("/api/video/v1/events/picture",jsonBody);
        System.out.println("result结果示例: " + result.getData());
        if(ObjectUtils.isNotEmpty(result.getData())){
            return result.getData().toString();
        }
        return null;

    }
    //回放地址
    @Override
    public Event playbackURLs(String cameraIndexCode,String beginTime,String endTime) {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("cameraIndexCode", cameraIndexCode);
        jsonBody.put("recordLocation", 1);
        jsonBody.put("transmode", 0);
        jsonBody.put("beginTime", beginTime);
        jsonBody.put("endTime", endTime);
        jsonBody.put("expand", "");
        jsonBody.put("streamform", "rtp");
        jsonBody.put("lockType", 0);
        jsonBody.put("protocol", "rtsp");

        Result result = hikRequest("/api/video/v1/cameras/playbackURLs",jsonBody);
        System.out.println("result结果示例: " + result);
        String data = result.getData().toString();
        System.out.println(data);
        Event event = new Event();
        event.setRemark(data.substring(data.indexOf("beginTime\":\"")+12,data.indexOf("\",\"endTime")));
        return event;
    }
    //预览地址
    @Override
    public String previewURLs(String code) {
        JSONObject jsonBody = new JSONObject();
//        jsonBody.put("cameraIndexCode", "604ee118e49549beb9bb82a5448bec0a");
        jsonBody.put("cameraIndexCode", code);
        jsonBody.put("streamType", 0);
        jsonBody.put("transmode", 1);
        jsonBody.put("protocol", "ws");
        jsonBody.put("expand", "transcode=0");
        jsonBody.put("streamform", "ps");

        Result result = hikRequest("/api/video/v2/cameras/previewURLs",jsonBody);
        System.out.println("result结果示例: " + result);
        if(ObjectUtils.isEmpty(result.getData())){
            return null;
        }
        String data = result.getData().toString();
        System.out.println("================");
        System.out.println(data);
        System.out.println(data.substring(data.indexOf("ws://"),data.indexOf("\"}")));
        System.out.println("================");
        return data.substring(data.indexOf("ws://"),data.indexOf("\"}"));
    }
    //获取区域信息
    @Override
    public List<Area> nodesByParams() {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("resourceType", "region");
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 100);


        Result result = hikRequest("/api/irds/v2/region/nodesByParams",jsonBody);
        System.out.println("result结果示例: " + result);
        PageHik pageHik = JSON.parseObject(result.getData().toString(), PageHik.class);
        System.out.println(pageHik.getList());
        List<Area> list = new ArrayList<>();
        for(Object o : pageHik.getList()){
            Region region = JSON.parseObject(o.toString(), Region.class);
            System.out.println("result结果示例: " + result);
            Area area = new Area();
            BeanUtils.copyProperties(region,area);
            area.setAreaCode(region.getIndexCode());
            list.add(area);
        }
        return list;
    }
    //获取摄像头在线状态（暂时不用）
    @Override
    public Map<String, String> getCameraOnline(String[] ids) {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("indexCodes", ids);
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 1000);
        Result result = hikRequest("/api/nms/v1/online/camera/get",jsonBody);
        System.out.println("+++++++++++++++++++++++++++++");
        System.out.println("result结果示例: " + result);
        PageHik pageHik = JSON.parseObject(result.getData().toString(), PageHik.class);
        Map<String, String> map = new HashMap<>();
        if(ObjectUtils.isEmpty(pageHik.getList())){
            return map;
        }
        for(Object o:pageHik.getList()){
            HashMap<String,Object> camera = JSON.parseObject(o.toString(), HashMap.class);
            map.put(camera.get("indexCode").toString(),camera.get("online").toString());
        }
        return map;
    }
    //将rtsp流保存为mp4文件,会一直提示，不用管
    @Override
    public void saveRtspToMp4(Event event, String outputPath, LocalDateTime startTime,LocalDateTime endTime) throws Exception {

    }

    //调用海康接口
    private Result hikRequest(String url, JSONObject jsonBody){
        List<SysDictData> list = sysDictDataMapper.selectDictDataByType("hik_setting")   ;
        Map<String, String> resultMap = list.stream()
                .collect(Collectors.toMap(
                        item -> item.getDictLabel(),
                        item -> item.getDictValue()
                ));
        /**
         * STEP1：设置平台参数，根据实际情况,设置host appkey appsecret 三个参数.
         */
        System.out.println(resultMap);
        ArtemisConfig.host = resultMap.get("host"); // 平台的ip端口
        ArtemisConfig.appKey = resultMap.get("appKey");  // 密钥appkey
        ArtemisConfig.appSecret = resultMap.get("appSecret");// 密钥appSecret
//        ArtemisConfig.host = host; // 平台的ip端口
//        ArtemisConfig.appKey = appKey;  // 密钥appkey
//        ArtemisConfig.appSecret = appSecret;// 密钥appSecret
        System.out.println(ArtemisConfig.host);
        System.out.println(ArtemisConfig.appKey);
        System.out.println(ArtemisConfig.appSecret);
        /**
         * STEP2：设置OpenAPI接口的上下文
         */
        final String ARTEMIS_PATH = resultMap.get("path");
//        final String ARTEMIS_PATH = path;

        /**
         * STEP3：设置接口的URI地址
         */
        final String previewURLsApi = ARTEMIS_PATH + url;
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put(resultMap.get("pathKey"), previewURLsApi);//根据现场环境部署确认是http还是https
//                put(pathKey, previewURLsApi);//根据现场环境部署确认是http还是https
            }
        };

        /**
         * STEP4：设置参数提交方式
         */
        String contentType = "application/json;charset=UTF-8";

        /**
         * STEP5：组装请求参数
         */
        String body = jsonBody.toJSONString();
        /**
         * STEP6：调用接口
         */
        String jsonString = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType , null);// post请求application/json类型参数
        System.out.println(body);
        System.out.println(jsonString);
        Result r = null;
        if(jsonString!=null){
            r=  JSON.parseObject(jsonString, Result.class);
        }

        return r;
    }


}
